﻿// // ******************************************************************
// //       /\ /|       @file       JwtHelper.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-06 20:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-03 14:11 Await
// // ******************************************************************

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AutomaticSubtitles.Service.DataAccess.Model;
using Masa.Contrib.Authentication.Identity;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace AutomaticSubtitles.Service.Infrastructure.Helper;

public class JwtHelper
{
    /// <summary>
    ///     生成token
    /// </summary>
    /// <param name="claimsIdentity"></param>
    /// <returns></returns>
    public static string GeneratorAccessToken(ClaimsIdentity claimsIdentity)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(JwtSecret);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = claimsIdentity,
            Expires = DateTime.UtcNow.AddHours(JwtEffectiveHours),
            SigningCredentials =
                new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }

    public static ClaimsIdentity GetClaimsIdentity(Auto_User user)
    {
        return new ClaimsIdentity(new Claim[]
        {
            new(ClaimType.DEFAULT_USER_ID, user.Id.ToString()),
            new("avatar", user.Avatar ?? ""),
            new(ClaimType.DEFAULT_USER_NAME, user.NickName)
        });
    }


    /// <summary>
    /// Swagger添加Jwt功能
    /// </summary>
    /// <param name="options"></param>
    public static void AddSwaggerAddJwtHeader(SwaggerGenOptions options)
    {
        options.AddSecurityRequirement(new OpenApiSecurityRequirement()
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                new string[] { }
            }
        });
        options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可，注意两者之间有空格",
            Name = "Authorization",        //jwt默认的参数名称
            In = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
            Type = SecuritySchemeType.ApiKey,
            BearerFormat = "JWT",
            Scheme = "Bearer"
        });
    }
}